<template>
  <d2-container>
    <el-row :gutter="20">
      <el-col :span="5">
        <el-scrollbar class="w-full h-full">
          <area-tree @nodeChange="treeNodeChange"></area-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="19">
        <div>
          <el-form label-position="right" :model="dataForm" :inline="true">
            <el-form-item class="el-form-item--mini" label="分类能耗：">
          <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="small">
            <el-option
              v-for="(item, index) in meterTypeList" :key="index"
              :label="item.paramValue"
              :value="item.paramKey">
            </el-option>
          </el-select>
          <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:16px;" @click="getPowerDataList">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="flex mt-4">
          <div class="p-4 flex-1 mr-4" style="background-color:rgba(0,0,0,.1);">
            <div class="theme-front-color"><span class="signLine"></span>环比</div>
            <div class="grid gap-3 grid-cols-3 mt-3">
              <div class="border px-2 text-center flex flex-col items-center justify-center" :style="{'border-color': activeSetting.name === 'd2' ? '#999' : '#999'}" style="height:90px;" v-for="(i, index) in list" :key="index">
                <div class="text-white theme-front-color font-bold text-lg">{{i.value}}</div>
                <div v-if="i.relativeValue" class="text-white theme-front-color font-bold text-base" :style="{'border-top': activeSetting.name === 'd2' ? 'solid 1px #999' : 'solid 1px #999'}">{{i.relativeValue}}{{currentUnit}}</div>
                <div class="text-sm theme-front-color">{{i.title == '趋势'?i.title:i.title+'('+currentUnit+')' }}</div>
              </div>
            </div>
          </div>
          <div class="p-4 flex-1 flex flex-col" style="background-color:rgba(0,0,0,.1);">
            <div class="flex items-center">
              <span class="theme-front-color flex-1"><span class="signLine"></span>能耗趋势</span>
              <el-radio-group v-model="dataForm.dateType" size="small" @change="getPowerList">
                <el-radio-button label="date" >当日</el-radio-button>
                <el-radio-button label="month" >当月</el-radio-button>
                <el-radio-button label="year" >当年</el-radio-button>
              </el-radio-group>
            </div>
            <div class="flex-1" id="energyUse_analysis_bar"></div>
          </div>
        </div>

        <div class="flex mt-4">
          <div class="p-4 flex-1" style="background-color:rgba(0,0,0,.1);">
            <!--<div class="theme-front-color"><span class="signLine"></span>日能耗</div>-->
            <div class="flex items-center"  style="display: flex;justify-content: flex-end;">
              <el-radio-group v-model="dataForm.dateTbType" size="small" @change="getTbPowerList">
                <el-radio-button label="date" >当日</el-radio-button>
                <el-radio-button label="month" >当月</el-radio-button>
                <el-radio-button label="year" >当年</el-radio-button>
              </el-radio-group>
            </div>
            <div class="flex-1" id="energyUse_analysis_line" style="min-height:300px;"></div>
          </div>
          <!--<div class="p-4 flex flex-col ml-4" style="background-color:rgba(0,0,0,.1);width:220px;"  v-if="showElectro">-->
            <!--<div class="theme-front-color"><span class="signLine"></span>功率峰值</div>-->
            <!--<div class="flex-1 flex flex-col">-->
              <!--<div class="border text-center flex-1 flex flex-col mt-4" :style="{'border-color': activeSetting.name === 'd2' ? '#999' : '#999'}" v-for="(i, index) in cards" :key="index">-->
                <!--<div class="flex-1 flex flex-col px-2 items-center justify-center text">-->
                  <!--<div class="theme-front-color font-bold text-2xl">{{i.value}}</div>-->
                  <!--<div class="theme-front-color text-sm">{{i.time}}</div>-->
                <!--</div>-->
                <!--<div :style="{'background-color': activeSetting.name === 'd2' ? '#409EFF' : '#409EFF'}" class="py-2 text-white">{{i.title}}</div>-->
              <!--</div>-->
            <!--</div>-->
          <!--</div>-->
        </div>
      </el-col>
    </el-row>
  </d2-container>
</template>

<script>
  import { mapGetters } from 'vuex'
  import areaTree from './compont/area_tree_onceclick'
  import * as echarts from 'echarts'
  import * as Util from "@/utils";
  import Config from "@/utils/config";
  export default {
    name: 'energyUse',
    data() {
      return {
        buildList:'',
        showElectro: false,
        dataForm:{
          energyType: '',
          date:new Date(),
          dateType: 'date',
          dateTbType: 'date',
          dayDate: Util.dateFormat('YYYYmmdd', new Date()),
          monthDate: Util.dateFormat('YYYYmm', new Date()),
          yearDate: Util.dateFormat('YYYY', new Date())
        },
        resultVal:{
          currentDayValue: '',
          lastDayValue: '',
          dayIncValue: '',
          dayIncRate: '',
        },
        meterTypeList:[],
        currentUnit:'',
        list: [
          {
            title: '今日用能',
            value: '--'
          },
          {
            title: '昨日同期',
            value: '--'
          },
          {
            title: '趋势',
            value: '--',
            relativeValue: '--'
          },
          {
            title: '当月用能',
            value: '--'
          },
          {
            title: '上月同期',
            value: '--'
          },
          {
            title: '趋势',
            value: '--',
            relativeValue: '--'
          },
          {
            title: '今年用能',
            value: '--'
          },
          {
            title: '去年同期',
            value: '--'
          },
          {
            title: '趋势',
            value: '--',
            relativeValue: '--'
          }
        ],
        cards: [
          {
            title: '当日(kW)',
            value: '12.94',
            time: '2023-02-05 09:00:00'
          },
          {
            title: '昨日(kW)',
            value: '14.16',
            time: '2023-02-04 09:00:00'
          }
        ],
      }
    },
    computed: {
      ...mapGetters('d2admin/theme', ['activeSetting'])
    },
    components: {
      areaTree
    },
    watch: {
      'activeSetting.name': {
        handler() {
          this.drawBar()
          this.drawLine()
        },
        immediate: true,
      },
        'dataForm.energyType':function(newV,oldV){
          this.currentUnit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
          if (this.dataForm.energyType != '010000') {
            this.showElectro = false
          }
          this.getPowerDataList()
        },
    },
    created() {
      this.$nextTick(()=>{
        this.queryStatic("METER_TYPE",null,data=>{
          if (data && data.code === 0) {
            this.meterTypeList = data.page
            this.dataForm.energyType = data.page[0].paramKey;
            this.currentUnit = data.page[0].paramExt;
          } else {
            this.meterTypeList = []
          }
           this.getPowerDataList();
        });
      })

    },
    methods: {
       treeNodeChange(data){
         this.buildList = data
         this.getPowerDataList();

      },
      getPowerDataList() {
        if(this.buildList && this.dataForm.energyType && this.buildList !=='') {
          this.getPowerList();
          this.getTbPowerList()

          this.$api.okhttp({
            url:this.$http.adornUrl('/eas/energyUse/list'),
            method: "post",
            data: this.$http.adornParams(
              {
                buildingIds: [this.buildList],
                meterType: this.dataForm.energyType,
                customerId: this.$util.cookies.get("customer_id"),
                projectId:this.$util.cookies.get("cuuren_projectId")
              }
            )
          }).then((data) => {
            if (data && data.code === 0) {
              let dataVal = data;
              this.list[0].value = dataVal.currentDayValue
              this.list[1].value = dataVal.lastDayValue
              this.list[2].value = dataVal.dayIncRate
              this.list[2].relativeValue = dataVal.dayIncValue

              this.list[3].value = dataVal.currentMonthValue
              this.list[4].value = dataVal.lastMonthValue
              this.list[5].value = dataVal.monthIncRate
              this.list[5].relativeValue = dataVal.monthIncValue

              this.list[6].value = dataVal.currentYearValue
              this.list[7].value = dataVal.lastYearValue
              this.list[8].value = dataVal.yearIncRate
              this.list[8].relativeValue = dataVal.yearIncValue

              this.showElectro = this.dataForm.energyType == '010000'

             // this.drawLine(dataVal.currentDayYNValue,dataVal.yesDayYNValue)
              this.cards[0].value = dataVal.currentDayMaxVal
              this.cards[0].time =  dataVal.currentDayMaxValTime
              this.cards[1].value = dataVal.lastDayMaxVal
              this.cards[1].time = dataVal.lastDayMaxValTime
            }
          }).catch(()=>{
          })
        }
      },
      formarDate(type, date) {
        return Util.dateFormat(Config.searchDate.find(item => item.date == type).format, date)
      },
      getPowerList() {
        const chart = echarts.init(document.querySelector('#energyUse_analysis_bar'))
        chart.clear()
        this.dataForm.date = new Date();
        this.$api.okhttp({
          url:this.$http.adornUrl('/eas/dmyReport/list'),
          method: "post",
          data: this.$http.adornParams(
            {
              buildingIds: [this.buildList],
              date: (this.dataForm.date&&this.dataForm.date!="")? this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date)):'',
              dateType: Config.searchDate.find(item=>item.date==this.dataForm.dateType).typeDesc,
              meterType: this.dataForm.energyType,
              customerId: this.$util.cookies.get("customer_id"),
              projectId:this.$util.cookies.get("cuuren_projectId")
            }
          )
        }).then((data) => {
          if (data && data.code === 0&&data.data.length>0) {
            let val = data.data[0].val;

            let valueArry = []
            Object.keys(val).forEach((key) => {
              valueArry.push({"id":key,"value":val[key]})
            })

            valueArry = this.objArraySort(valueArry, "id")

            let xMax = 0;
            if(this.dataForm.dateType == 'date'){
               xMax = new Date().getHours()+1;

            }else if(this.dataForm.dateType == 'month'){
               xMax = new Date().getDate();

            } else if(this.dataForm.dateType == 'year'){
               xMax = new Date().getMonth()+1;
            }
            console.log(1111,valueArry)
            valueArry = valueArry.slice(0,xMax)
            let xdata = valueArry.map(i=>i.id)
            let ydata = valueArry.map(i=>i.value)

            this.drawBar(xdata,ydata)
          }
        })

      },

      getTbPowerList() {
        let dateType = Config.searchDate.find(item=>item.date==this.dataForm.dateTbType).typeDesc
        let date= ''
        if(dateType == "1") {
          date = this.dataForm.dayDate;
        }else if(dateType == "2") {
          date = this.dataForm.monthDate
        }else if(dateType == "3") {
          date =  this.dataForm.yearDate
        }
        this.$api.okhttp({
          url:this.$http.adornUrl('/eas/energyTrend/list'),
          method: "post",
          data: this.$http.adornParams(
            {
              buildingIds: [this.buildList],
              date: date,
              dateType: dateType,
              meterType: this.dataForm.energyType,
              customerId: this.$util.cookies.get("customer_id"),
              projectId:this.$util.cookies.get("cuuren_projectId")
            }
          )
        }).then((data) => {
          if (data && data.code === 0) {
            let valueArry = []
            let valueLastArry = []
            if(data.data.length>0) {
              let val = data.data[0].val;
              Object.keys(val).forEach((key) => {
                valueArry.push({"id": key, "value": val[key]})
              })
              valueArry = this.objArraySort(valueArry, "id")
            }
            if(data.last.length>0) {
              let val = data.last[0].val;
              Object.keys(val).forEach((key) => {
                valueLastArry.push({"id": key, "value": val[key]})
              })
              valueLastArry = this.objArraySort(valueLastArry, "id")
            }

            let xMax = 0;
            let ydataLast = []
            if(dateType == '1'){
              xMax = new Date().getHours();
              valueArry = valueArry.slice(0,xMax+1)
              let xdata = valueArry.map(i=>i.id)
              let ydata = valueArry.map(i=>i.value)
              ydataLast = valueLastArry.map(i=>i.value)
              this.drawLine(xdata,ydata,ydataLast,'今天','昨日')
            }else if(dateType == '2'){
              xMax = new Date().getDate();
              valueArry = valueArry.slice(0,31)
              let xdata = valueArry.map(i=>i.id)
              let ydata = valueArry.map(i=>i.value)
              ydataLast = valueLastArry.map(i=>i.value)
              this.drawLine(xdata,ydata,ydataLast,'当月','上月')
            } else if(dateType == '3'){
              xMax = new Date().getMonth()+1;
              valueArry = valueArry.slice(0,xMax)
              let xdata = valueArry.map(i=>i.id)
              let ydata = valueArry.map(i=>i.value)
              ydataLast = valueLastArry.map(i=>i.value)
              this.drawLine(xdata,ydata,ydataLast,'今年','去年')
            }
          }
        })

      },
      objArraySort(objArr, key)
      {
        let result = objArr.slice(0);
        return result.sort((a, b) => parseInt(a[key]) - parseInt(b[key]));
      },
      queryStatic(type,paramValue,callback) {
        let params = {
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        }
        if(paramValue){
          Object.assign(params,{paramValue,paramValue});
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },
      drawBar(xdata,ydata) {
        this.$nextTick(() => {
          const chart = echarts.init(document.querySelector('#energyUse_analysis_bar'))
          chart.clear()
          chart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            grid: {
              left: '10%',
              right: '5%',
              top: '19%',
              bottom: '10%'
            },
            xAxis: {
              type: 'category',
              data: xdata,
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
            },
            yAxis: {
              name: this.currentUnit,
              nameTextStyle: {
                align: "right"
              },
              type: 'value',
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: ['#999']
                },
              },
            },
            series: [
              {
                data: ydata,
                type: 'bar',
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                }
              }
            ]
          })
        })
      },
      drawLine(xdata,currentDayGlValue,lastDayGLValue,dateName,lastdateName) {
        this.$nextTick(() => {
          const chart = echarts.init(document.querySelector('#energyUse_analysis_line'))
          chart.resize()
          chart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            grid: {
              left: '2%',
              right: '2%',
              top: '15%',
              bottom: '5%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: xdata,
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
            },
            yAxis: {
              type: 'value',
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: ['#999']
                },
              },
            },
            legend: {
              textStyle: {
                color: this.activeSetting.name === 'd2' ? '#333' : '#ccc'
              },
            },
            series: [
              {
                data: lastDayGLValue,
                type: 'line',
                smooth: true,
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                },
                name: lastdateName,
              },
              {
                data: currentDayGlValue,
                type: 'line',
                smooth: true,
                name: dateName,
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                }
              }
            ]
          })
        })
      },
    },
  }
</script>

<style>
  .signLine{
    display: inline-block;
    width: 4px;
    height: 15px;
    background-color: #409eff;
    margin-right: 6px;
    vertical-align: -2px;
  }
</style>
